var exec = require('child_process').exec;
var fs = require('fs');
var rd = require('rd');
var json2csv = require('json2csv');
var sdkList = [{sdk: "com.pingplusplus.android.PaymentActivity", name: "银联支付"},
    {sdk: "com.baidu.android.pushservice", name: "百度云推送"}, {sdk: "com.igexin.sdk", name: "个推推送"},
    {sdk: "cn.jpush.android.service", name: "极光推送"}, {sdk: "com.alipay.sdk", name: "支付宝支付"},
    {sdk: "com.yintong", name: "连连支付"}, {sdk: "com.umeng.message", name: "友盟推送"},
    {sdk: "cn.sharesdk", name: "ShareSDK"}, {sdk: "cn.smssdk", name: "短信验证码SDK"},
    {sdk: "com.tencent.android.tpush", name: "腾讯信鸽推送"}, {sdk: "com.baidu.cloudsdk.social", name: "百度社会化分享"},
    {sdk: "com.baidu.wallet", name: "百度钱包"}, {sdk: "com.umeng.socialize", name: "友盟社会化分享"},
    {sdk: "com.tencent.mm.plugin.openapi.Intent", name: "微信支付"},
    {sdk: "com.xiaomi.push.service", name: "小米推送"}, {sdk: "com.huawei.android.push", name: "华为推送"},
    {sdk: "com.bshare", name: "bshare分享"}, {sdk: "com.avos.avoscloud.PushService", name: "LeanCloud推送"},
    {sdk: "com.baidu.mapapi", name: "百度地图"}, {sdk: "com.amap.api", name: "高德地图"},
    {sdk: "com.google.android.maps", name: "谷歌地图"}, {sdk: "com.tencent.tencentmap.mapsdk", name: "腾讯地图"},
    {sdk: "com.mapbar.android", name: "图吧地图"}, {sdk: "com.tencent.sample", name: "腾讯QQ互联平台"},
    {sdk: "com.xiaomi.account.openauth", name: "小米账号登录"}, {sdk: "com.qihoopay.insdk", name: "360登录"},
    {sdk: "com.megvii.facepp", name: "Face++人脸识别"}, {sdk: "com.iflytek.cloud.FaceDetector", name: "讯飞人脸识别"},
    {sdk: "com.iflytek.speech", name: "讯飞开放平台语音识别"}, {sdk: "com.baidu.voicerecognition", name: "百度语音语音识别"},
    {sdk: "com.unisound.client.SpeechConstants", name: "云知声语音识别"},


    {sdk: "com.turing.androidsdk", name: "图灵机器人"}, {sdk: "com.hyphenate.chat", name: "环信即时通讯云"},
    {sdk: "io.rong.imlib", name: "融云即时通讯云"}, {sdk: "com.pingplusplus.android.PaymentActivity", name: "Ping++支付"},
    {sdk: "cn.bmob.v3.Bmob", name: "Bmob云存储"}, {sdk: "cn.bmob.push", name: "Bmob推送"},
    {sdk: "com.yuntongxun.ecsdk", name: "容联·云通讯语音服务"}, {sdk: "com.qiniu.android", name: "七牛云存储"},
    {sdk: "com.upyun.library", name: "又拍云云存储"}, {sdk: "com.upyun.push", name: "又拍云 直播"},
    {sdk: "com.qq.wx.voice", name: "微信语音"}, {sdk: "cn.bmob.pay", name: "Bmob支付"},
    {sdk: "com.gotye.gotyeliveapp", name: "亲加语音通讯云直播"}, {sdk: "com.gotye.api.GotyeAPI", name: "亲加语音通讯云即时通讯"},
    {sdk: "com.gotye.service.AiLiaoService", name: "亲加语音通讯云实时语音"}, {sdk: "com.meiqia.meiqiasdk", name: "美洽"},
    {sdk: "cn.beecloud", name: "BeeCloud支付"}, {sdk: "com.yzx.im", name: "云之讯IM"},
    {sdk: "com.isnc.facesdk", name: "一登人脸识别"}, {sdk: "com.gizwits.gizwifisdk", name: "机智云"},
    {sdk: "org.lasque.tusdk", name: "TuSDK图片处理"}, {sdk: "cn.udesk.activity", name: "Udesk客服"},
    {sdk: "com.chosen.kf5sdk", name: "逸创云客服"}, {sdk: "com.wilddog.client", name: "野狗"},
    {sdk: "cn.com.duiba.credits", name: "兑吧"}, {sdk: "com.sobot.chat", name: "智齿"},
    {sdk: "com.inmobi.monetization", name: "inmobi"}, {sdk: "com.mobisage.android", name: "艾德思奇"},
    {sdk: "com.imopan.ad.sdk", name: "磨盘网络"}
];

//传入apk文件路径，解析apk包
var files = rd.readSync(process.argv[2]);
var matchingResult = [];
var myCars = [];
var fields = "apkFileUrl";
sdkList.forEach(function (item) {
    fields += "," + item.name
});

var index0 = 1;
var index1 = 2;
var index2 = 3;
var index3 = 4;
var index4 = 5;
function analysisApkFile() {
    var dataFile = fs.statSync(files[index0]);
    if (dataFile.isFile()) {
        childProcess(files[index0]);
        childProcess(files[index1]);
        childProcess(files[index2]);
        childProcess(files[index3]);
        childProcess(files[index4]);
    }
}

function childProcess(item) {
    if (!item) {
        return;
    }
    console.log(new Date().toLocaleTimeString() + "解析开始")
    var child = exec('apktool d ' + item, {maxBuffer: 1024 * 500}, function (err, stdout, stderr) {
        if (err) console.log(err);
        console.log(new Date().toLocaleTimeString() + "解析结束")
        getFolderUrl(item);
    });
}

function getFolderUrl(item) {
    var url = item.split("/");
    readAllFile(url[url.length - 1].slice(0, -4), item.slice(0, item.indexOf(url[url.length - 1])));
}

function readAllFile(apkFileUrl, withUrl) {
    var files = rd.readSync(apkFileUrl);
    console.log(new Date().toLocaleTimeString() + "匹配开始")
    for (var j = 0; j < files.length; j++) {
        if (files[j].indexOf(apkFileUrl + "/res") != -1 || files[j].indexOf(".png") != -1 ||
            files[j].indexOf(apkFileUrl + "/assets") != -1 || files[j].indexOf(apkFileUrl + "/lib") != -1) {
            continue
        } else {
            isFIle(files[j])
        }
    }
    fs.open("tian", "wx+", function (err, fd) {
        if (err) {
            return
        }
        fs.write(fd, fields + "\n", function (err) {
            if (err) return console.error(err);
            console.log("创建文件");
        })
    });
    console.log(new Date().toLocaleTimeString() + "匹配结束")
    saveResult(apkFileUrl, withUrl)
}

function isFIle(url) {
    for (var i = 0; i < sdkList.length; i++) {
        try {
            var dataFile = fs.statSync(url);
            if (dataFile.isFile()) {
                getFile(url, i)
            }
        } catch (err) {
            console.log(err);
            return false
        }
    }
    return false;
}

function getFile(url, i) {
    var data = fs.readFileSync(url);
    var filter = new RegExp(sdkList[i].sdk, "i");

    if (filter.test(data.toString())) {
        matchingResult.push(sdkList[i].name);
    }
}

function saveResult(apkFileUrl, withUrl) {
    var data = apkFileUrl;
    sdkList.forEach(function (item) {
        if (matchingResult.indexOf(item.name) != -1) {
            data += "," + 1;
        } else {
            data += "," + 0;
        }
    });
    //myCars.push(data);
    //var csv = json2csv({data: myCars, fields: fields});
    //console.log(csv)
    //fs.writeFile("tian", csv, function (err) {
    //    if (err) return console.error(err+"xxxxx");
    //    matchingResult = [];
    //    console.log(new Date().toLocaleTimeString() + "数据写入成功！")
    //    if (index < files.length - 1) {
    //        index += 2;
    //        index1 += 2;
    //        childProcess(files[index]);
    //        childProcess(files[index1]);
    //    }
    //});
    //fs.appendFile("tian", data + "\n", function () {
    //    console.log("+++++++++++++++++")
    //    matchingResult = [];
    //
    //    console.log(new Date().toLocaleTimeString() + "数据写入成功！")
    //    //if (index0 < files.length - 1) {
    //    childProcess(files[files.indexOf(withUrl + apkFileUrl + ".apk") + 5]);
    //    //}
    //});
    fs.open("tian", "a+", function (err, fd) {
        if (err) {
            return console.error(err);
        }
        fs.write(fd, data + "\n", function (err) {
            if (err) return console.error(err);
            matchingResult = [];
            console.log(new Date().toLocaleTimeString() + "数据写入成功！")
            //if (index0 < files.length - 1) {
            fs.close(fd, function(err){
                if (err){
                    console.log(err);
                }
                console.log("文件关闭成功");
                childProcess(files[files.indexOf(withUrl + apkFileUrl + ".apk") + 5]);
            });
            //}
        });
    });
}

analysisApkFile();
